package com.aidex.web.controller.tool;



import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class XunSuBangAesUtils {

    /**
     * 加密
     * @param str
     * @param key
     * @return
     */
    public static String encrypt(String str, String key) {
        try {
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encrypted = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }


    /**
     * 解密
     * @param sSrc
     * @param sKey
     * @return
     */
    public static String decrypt(String sSrc, String sKey){
        try {
            byte[] raw = sKey.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // 先用 base64 解密
            byte[] encrypted1 = new Base64().decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                return new String(original, StandardCharsets.UTF_8);
            } catch (Exception e) {

                return null;
            }
        } catch (Exception e) {

            return null;
        }
    }

    public static void main(String[] args) {
        String key = "YJA5F60ff5N23Rsk";
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("cusName","xiongdada");
        jsonObject.put("cusId","123456");
        jsonObject.put("phone","12345678901");
        jsonObject.put("cityName","宜昌");
        String encryptData = encrypt(jsonObject.toJSONString(), key);
        System.out.println("加密内容:" + encryptData);
        String decryptData = decrypt(encryptData, key);
        System.out.println("解密内容：" + decryptData);
    }
}
